package com.jaydenxiao.common.baseapp;

import android.util.Log;

import com.jaydenxiao.common.actionUtil.BaseSPUtils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by hasee on 2017/10/10.
 */

public class BaseApiService {

    public static final String BASE_URL="http://www.zjsos.net:19002/";
    public static final String USER_ACTION_URL="http://www.zjsos.net:19002/appbehavior/save";
//    public static final String BASE_URL="http://192.168.9.17:8089/soscode/news?id=40288991604dc25c01604dc276750000";
    public static final String GET_ACTION_URL="http://www.zjsos.net:8888/http/zjs/userActionUrl.txt";
    public static final String APK_VERSION_URL=
            "http://www.zjsos.net:8888/http/haiyang/androidPad/androidPad_updates_apk.json";
    public static final String SHIP_DATA_VERSION_URL=
            "http://www.zjsos.net:8888/http/haiyang/androidPad/androidPad_updates_cert.json";
    public static final int NO_COOKIE=0;
    public static final int SAVE_COOKIE =1;
    public static final int SET_COOKIE=2;


    public static BaseHttpService getBaseHttpService(int cookieType,boolean responseIsString){

        OkHttpClient.Builder okBuilder=new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS);
        switch (cookieType){
            case SAVE_COOKIE:
                okBuilder.addInterceptor(saveCookieInterceptor());
                break;
            case SET_COOKIE:
                okBuilder.addInterceptor(putCookieInterceptor());
                break;
            case NO_COOKIE:
            default:
                break;
        }

        Converter.Factory factory;
        if (responseIsString){
            factory=StringConverterFactory.creat();
        }else {
            factory=GsonConverterFactory.create();
        }
        OkHttpClient client=okBuilder.build();
        Retrofit retrofit=new Retrofit.Builder()
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(factory)
                .client(client)
                .baseUrl(BASE_URL)
                .build();
        return retrofit.create(BaseHttpService.class);
    }



    public static Interceptor saveCookieInterceptor(){
        Interceptor interceptor=new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Response response=chain.proceed(chain.request());

                if (!response.header("Set-Cookie").isEmpty()){
                    Observable.just(response.header("Set-Cookie"))//发射一个数据
                            .map(new Function<String, String>() {//处理并且返回数据

                                @Override
                                public String apply(@NonNull String s) throws Exception {
//                                    String[] cookieArray=s.split(";");
//                                    return cookieArray[0];
                                    return s;
                                }
                            }).subscribe(new Consumer<String>() {
                        @Override
                        public void accept(String s) throws Exception {
                            Log.e("secondSaveCookie",s);
                            BaseSPUtils.setSharedStringData(BaseApplication.getAppContext(),BaseSPUtils.COOKIE,s);
                        }
                    });

                }
                return response;
            }
        };
        return interceptor;
    }

    public static Interceptor putCookieInterceptor(){
        Interceptor interceptor=new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request.Builder request=chain.request().newBuilder();
                String cookie=BaseSPUtils.getSharedStringData(BaseApplication.getAppContext(),BaseSPUtils.COOKIE);
                request.addHeader("Cookie",cookie);
                Log.e("getCookie",cookie);
                return chain.proceed(request.build());
            }
        };
        return interceptor;
    }





}
